package eiisan.config.swagger;

import com.fasterxml.classmate.TypeResolver;
import com.google.common.base.Predicates;
import eiisan.config.security.settings.SecurityProperties;
import eiisan.constant.settings.PropertyKey;
import eiisan.util.model.response.Result;
import eiisan.util.model.response.ResultCode;
import eiisan.util.spring.PropertyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMethod;
import springfox.documentation.builders.*;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.time.LocalDate;
import java.util.*;
import java.util.Map.Entry;
import java.util.stream.Collectors;

/**
 * swagger配置
 */

@EnableSwagger2
@Configuration
@Profile({ "dev", "test" })
public class SwaggerConfig {

    /** 访问控制参数配置 */
    @Autowired
    private SecurityProperties securityProperties;
    /** swagger参数配置 */
    @Autowired
    private SwaggerProperties swaggerProperties;

    /** 主配置 */
    @Bean
    public Docket petApi() {
        List<ResponseMessage> responseMessageList = getGlobalResponseMessage();

        return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage()))
                        .paths(PathSelectors.any()).build()
                        .apiInfo(apiInfo())
                        //.pathMapping(PropertyUtil.get(PropertyKey.Web.BASE_PATH))
                        .directModelSubstitute(LocalDate.class, String.class)     //将LocalDate类型全部转为String类型
                        .genericModelSubstitutes(ResponseEntity.class)
                        .additionalModels(new TypeResolver().resolve(Result.class))
                        .useDefaultResponseMessages(false)

                        .securitySchemes(Collections.unmodifiableList(Arrays.asList(apiKey())))
                        .securityContexts(Collections.unmodifiableList(Arrays.asList(securityContext())))

                        .enableUrlTemplating(false)

                        .globalResponseMessage(RequestMethod.GET,responseMessageList)
                        .globalResponseMessage(RequestMethod.POST, responseMessageList)
                        .globalResponseMessage(RequestMethod.PUT, responseMessageList)
                        .globalResponseMessage(RequestMethod.DELETE,responseMessageList)

                        .globalOperationParameters(getGlobalOperationParameters())
                ;
    }

    private List<ResponseMessage> getGlobalResponseMessage() {
        List<ResponseMessage> list = new ArrayList<>();
        Map<HttpStatus, List<ResultCode>> map = new HashMap<>();
        for (ResultCode item : ResultCode.values()) {
            if (map.containsKey(item.getHttpStatus())) {
                map.get(item.getHttpStatus()).add(item);
            } else {
                List<ResultCode> codeList = new ArrayList<>();
                codeList.add(item);
                map.put(item.getHttpStatus(), codeList);
            }
        }
        for (Entry<HttpStatus, List<ResultCode>> entry : map.entrySet()) {
            String message = String.join(" | ", entry.getValue().stream().map((iter) -> {
                return iter.getDesc() + ",自定义状态码:" + iter.getCode();
            }).collect(Collectors.toList()));
            list.add(new ResponseMessageBuilder().code(entry.getKey().value()).message(message).responseModel(
                    new ModelRef(Result.class.getName())).build());
        }
        return list;
    }

    private List<Parameter> getGlobalOperationParameters() {
        // tokenClaim = securityProperties.getJwt().getAuthorityClaim();
        String tokenHeader = securityProperties.getJwt().getHeader();
        String tokenPrefix = securityProperties.getJwt().getTokenPrefix();
        List<Parameter> pars = new ArrayList<>();
        ParameterBuilder ticketPar = new ParameterBuilder();
        ticketPar.name(tokenHeader)
                .description("token,除免验证url外均必填")
                .parameterType("header")
                .defaultValue(tokenPrefix)
                .modelRef(new ModelRef("string"))
                .required(false)
                .build();
        pars.add(ticketPar.build());
        return pars;
    }

    /** 配置说明 */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title(swaggerProperties.getTitle()).description(swaggerProperties.getDescription())
                .contact(new Contact(swaggerProperties.getAuthor(), swaggerProperties.getDocUrl(), swaggerProperties.getEmail())).version("1.0").build();
    }

    /** 配置token */
    private ApiKey apiKey() {
        return new ApiKey(securityProperties.getJwt().getTokenPrefix(), securityProperties.getJwt().getHeader(),"header");
    }

    /** 配置访问路径 */
    private SecurityContext securityContext() {
        // 注意要与RestfulAPI路径一致
        return SecurityContext.builder()
                .securityReferences(defaultAuth())
                .forPaths(PathSelectors.regex(PropertyUtil.get(PropertyKey.Web.BASE_PATH)))
                .build();
    }

    /** 默认验证配置 */
    private List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        return Arrays.asList(new SecurityReference(securityProperties.getJwt().getTokenPrefix(), authorizationScopes));
    }
}
/*

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Value("${jwt.header}")
    private String tokenHeader;

    @Value("${swagger.enabled}")
    private Boolean enabled;

    @Bean
    public Docket createRestApi() {
        ParameterBuilder ticketPar = new ParameterBuilder();
        List<Parameter> pars = new ArrayList<Parameter>();
        ticketPar.name(tokenHeader).description("token")
                .modelRef(new ModelRef("string"))
                .parameterType("header")
                .defaultValue("Bearer ")
                .required(true)
                .build();
        pars.add(ticketPar.build());
        return new Docket(DocumentationType.SWAGGER_2)
                .enable(enabled)
                .apiInfo(apiInfo())
                .select()
                .paths(Predicates.not(PathSelectors.regex("/error.*")))
                .build()
                .globalOperationParameters(pars);
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("eladmin 接口文档")
                .version("2.1")
                .build();
    }
}
*/
